package com.etoak.commons.util;



import org.apache.commons.collections4.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Set;


public class ValidatorUtil {


    public static final Validator validator;

    static {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        validator = factory.getValidator();
    }

    public  static  void  validate(Object obj){
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);

        if (CollectionUtils.isNotEmpty(constraintViolations)){

            StringBuffer  errorBuf = new StringBuffer();
            constraintViolations.forEach(violation ->{

                String field = violation.getPropertyPath().toString();
                //错误消息
                String  message = violation.getMessage();
                errorBuf.append(field).append(message).append(";");
            });
            //抛出异常
            throw new RuntimeException(errorBuf.toString());
        }
    }
}
